package com.hzhq.contract.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzhq.contract.bean.dto.DepartDTO;
import com.hzhq.contract.bean.entity.ContractType;
import com.hzhq.contract.bean.entity.Depart;
import com.hzhq.contract.bean.vo.ContractTypeVO;
import com.hzhq.contract.bean.vo.DepartVO;
import com.hzhq.contract.convert.ContractTypeConvertBasic;
import com.hzhq.contract.convert.DepartConvertBasic;
import com.hzhq.contract.result.Result;
import com.hzhq.contract.service.DepartService;
import com.hzhq.contract.status.DefaultValue;
import com.hzhq.contract.util.ConvertUtil;
import com.hzhq.contract.util.Page2ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: hzhq1255
 * @mail: hzhq1255@163.com
 * @date: 2021/4/15 12:42
 * @desc:
 */
@Slf4j
@CrossOrigin
@RestController
@ResponseBody
@Api(tags = "部门管理")
@RequestMapping("/api/v1/departs")
public class DepartController {


    @Autowired
    DepartService departService;


    @ApiOperation(value = "getOneByDepartId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departId",value = "部门id",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/departId/{departId}",method = RequestMethod.GET)
    public Result<Object> getOneByDepartId(@PathVariable("departId") @NotNull String departId){

        DepartDTO departDTO = departService.getOneByDepartId(departId);
        if (departDTO == null){
            return Result.error("没有该 "+ departId +" 部门");
        }
        DepartVO departVO = DepartConvertBasic.INSTANCE.dtoToVo(departDTO);
        return Result.success(departVO);
    }

    @ApiOperation(value = "getOneByDepartName")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departName",value = "部门",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/departName/{departName}",method = RequestMethod.GET)
    public Result<Object> getOneByDepartName(@PathVariable("departName") @NotNull String departName){
        DepartDTO departDTO = departService.getOneByDepartName(departName);
        if (departDTO == null){
            return Result.error("没有该 "+ departName +" 部门");
        }
        DepartVO departVO = DepartConvertBasic.INSTANCE.dtoToVo(departDTO);
        return Result.success(departVO);
    }

    @ApiOperation(value = "获取部门管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departName",value = "部门",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/departName/{departName}/admins",method = RequestMethod.GET)
    public Result<Object> getAdminListByDepartName(@PathVariable("departName") @NotNull String departName){
        List<HashMap<String,Object>> adminNameList = departService.getAdminListByDepartName(departName).stream().map(e -> {
            HashMap<String,Object> map = new HashMap<>(1);
            map.put("username",e);
            return map;
        }).collect(Collectors.toList());
        return Result.success(adminNameList);
    }


    @ApiOperation(value = "获取部门管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departId",value = "部门id",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/departId/{departId}/admins",method = RequestMethod.GET)
    public Result<Object> getAdminListByDepartId(@PathVariable("departId") @NotNull String departId){
        List<HashMap<String,Object>> adminNameList = departService.getAdminListByDepartId(departId).stream().map(e -> {
            HashMap<String,Object> map = new HashMap<>(1);
            map.put("username",e);
            return map;
        }).collect(Collectors.toList());
        return Result.success(adminNameList);
    }

    @ApiOperation(value = "部门列表List")
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public Result<Object> getAllList(){
        List<DepartDTO> departDTOList = departService.getAllList();
        return Result.success(departDTOList.stream().map(DepartConvertBasic.INSTANCE::dtoToVo));
    }

    @ApiOperation(value = "部门列表Page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage",value = "当前页",paramType = "path",dataTypeClass = Integer.class, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页个数",paramType = "path",dataTypeClass = Integer.class, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/currentPage/{currentPage}/pageSize/{pageSize}",method = RequestMethod.GET)
    public Result<Object> getAllPage(@PathVariable("currentPage") @NotNull Integer currentPage,
                                     @PathVariable("pageSize") @NotNull Integer pageSize){
        Page<DepartDTO> departDTOPage = departService.getAllPage(currentPage, pageSize);
        Page<DepartVO> departVOPage = departDTOPage.map(DepartConvertBasic.INSTANCE::dtoToVo);
        return Result.success(Page2ResultUtil.getPageData(departVOPage));
    }

    @ApiOperation("获取部门page")
    @ResponseBody
    @RequestMapping(value = "/search/query/currentPage/{currentPage}/pageSize/{pageSize}",method = RequestMethod.GET)
    public Result<Object> searchAllPageByQuery(@PathVariable("currentPage") @NotNull Integer currentPage,
                                               @PathVariable("pageSize") @NotNull Integer pageSize,
                                               @RequestParam("keyword") String keyword){
        final Query query = new Query();
        final Criteria criteria = new Criteria();
        List<Criteria> ands = new ArrayList<>();
        List<Criteria> ors = new ArrayList<>();
        if (keyword != null){
            ors.add(Criteria.where(Depart.DEPART_NAME_FIELD).regex("^.*"+keyword+".*$"));
            ors.add(Criteria.where(Depart.DESC_FIELD).regex("^.*"+keyword+".*$"));
            criteria.orOperator(ors.toArray(Criteria[]::new));
        }
        ands.add(Criteria.where(Depart.DELETED_FIELD).is(DefaultValue.NOT_DELETED));
        criteria.andOperator(ands.toArray(Criteria[]::new));
        query.addCriteria(criteria);
        Page<DepartVO> departVOS = departService.searchAllPageByQuery(query,currentPage, pageSize).map(DepartConvertBasic.INSTANCE::dtoToVo);
        return Result.success(Page2ResultUtil.getPageData(departVOS));
    }


    @ApiOperation(value = "保存部门")
    @ResponseBody
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result<Object> save(@RequestBody DepartDTO departDTO){
        ObjectId departId = departDTO.getDepartId();
        DepartDTO currentDepart = departService.getOneByDepartName(departDTO.getDepartName());
        if (departId == null){
            if (null != currentDepart){
                return Result.errorWithMsg("该部门已存在");
            }
            departDTO.setDeleted(DefaultValue.NOT_DELETED);
            return Result.successWithMsgAndData("添加成功",departService.save(departDTO).getDepartId());
        }
        else {
            if (null == currentDepart){
                return Result.errorWithMsg("该部门不存在");
            }
            BeanUtil.copyProperties(departDTO,currentDepart,new CopyOptions().ignoreNullValue());
            return Result.successWithMsgAndData("编辑成功",departService.save(currentDepart).getDepartId());
        }
    }


    @ApiOperation(value = "保存部门ALL")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departVOList",value = "departVOList",paramType = "body",dataTypeClass = DepartVO.class, dataType = "DepartVO"),
    })
    @ResponseBody
    @RequestMapping(value = "/saveAll",method = RequestMethod.POST)
    public Result<Object> saveAll(@RequestBody List<DepartVO> departVOList){
        List<DepartDTO> departDTOList = departService.saveAll(
                departVOList.stream().map(DepartConvertBasic.INSTANCE::voToDto).collect(Collectors.toList()));
        if (departDTOList == null){
            return Result.error("已存在或保存失败");
        }
        List<String> departIds = departDTOList.stream().map(e -> e.getDepartId().toString()).collect(Collectors.toList());
        return Result.success(departIds);
    }


    @ApiOperation(value = "删除byName")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departName",value = "部门",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/delete/departName/{departName}",method = RequestMethod.POST)
    public Result<Object> deleteByDepartName(@PathVariable("departName") @NotNull String departName){
        DepartDTO departDTO = departService.deleteByDepartName(departName);
        if (departDTO == null){
            return Result.error("删除失败或可能没有该部门");
        }
        return Result.success(departDTO.getDepartId().toString());
    }


    @ApiOperation(value = "删除byId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departId",value = "部门id",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/delete/departId/{departId}",method = RequestMethod.POST)
    public Result<Object> deleteByDepartId(@PathVariable("departId") @NotNull String departId){
        DepartDTO departDTO = departService.deleteByDepartId(departId);
        if (departDTO == null){
            return Result.error("删除失败或可能没有该部门");
        }
        return Result.success(departDTO.getDepartId().toString());
    }



    @ApiOperation(value = "删除byIds")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departIds",value = "部门ids",paramType = "form",dataTypeClass = List.class, dataType = "List")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    public Result<Object> deleteByDepartId(@RequestParam("departIds")  List<String> departIds){
        List<DepartDTO> departDTOList = departService.deleteAllByIds(departIds);
        if (departDTOList == null){
            return Result.error("删除失败");
        }
        return Result.success(departDTOList.stream().map(e -> e.getDepartId().toString()).collect(Collectors.toList()));
    }






}
